package org.jc.auth.domain.service.impl;

import com.google.gson.Gson;
import jakarta.annotation.Resource;
import org.jc.auth.common.enums.IsDeletedFlagEnum;
import org.jc.auth.common.redis.RedisUtil;
import org.jc.auth.domain.entity.AuthRolePermissionBO;
import org.jc.auth.domain.service.AuthRolePermissionDomainService;
import org.jc.auth.infra.basic.entity.AuthPermission;
import org.jc.auth.infra.basic.entity.AuthRolePermission;
import org.jc.auth.infra.basic.service.AuthPermissionService;
import org.jc.auth.infra.basic.service.AuthRolePermissionService;
import org.jc.auth.infra.basic.service.AuthRoleService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 功能描述
 *
 * @author wanghongqian
 * @date 2024/07/14 12:45
 */
@Service
public class AuthRolePermissionDomainServiceImpl implements AuthRolePermissionDomainService {

    private String authPermissionPrefix = "auth.permission";

    private String authRolePrefix = "auth.role";

    @Resource
    private AuthRolePermissionService authRolePermissionService;

    @Resource
    private AuthRoleService authRoleService;

    @Resource
    private AuthPermissionService authPermissionService;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public Boolean add(AuthRolePermissionBO authRolePermissionBO) {
        Long roleId = authRolePermissionBO.getRoleId();
        List<Long> permissionIdList = authRolePermissionBO.getPermissionIdList();
        List<AuthRolePermission> authRolePermissionList = new ArrayList<>();
        permissionIdList.forEach(permissionId -> {
            AuthRolePermission authRolePermission = new AuthRolePermission();
            authRolePermission.setRoleId(roleId);
            authRolePermission.setPermissionId(permissionId);
            authRolePermission.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
            authRolePermissionList.add(authRolePermission);
        });
        Integer count = authRolePermissionService.insertBatch(authRolePermissionList);

        /**
         * 角色-权限 的关系放进redis
         */
        List<AuthPermission> authPermissions = authPermissionService.queryByIds(permissionIdList);
        String roleKey = redisUtil.buildKey(authPermissionPrefix, roleId.toString());
        List<String> permissionKeys = authPermissions.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());
        redisUtil.set(roleKey,new Gson().toJson(permissionKeys));

        return count > 0;
    }
}
